#include ".\jsonconfigview.h"
#include <QVBoxLayout>
#include <QPushButton>
#include <QJsonDocument>
#include <QMessageBox>

JsonConfigView::JsonConfigView(QObject *parent)
    : ConfigView(parent)
{
    m_view = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout(m_view);
    mainLayout->setContentsMargins(10, 10, 10, 10);

    // 创建文本编辑框
    m_jsonEdit = new QTextEdit();
    m_jsonEdit->setReadOnly(false); // 允许编辑
    m_jsonEdit->setFont(QFont("Consolas", 10));
    m_jsonEdit->setStyleSheet(
        "QTextEdit {"
        "   background-color: #ffffff;"
        "   border: 1px solid #d0d0d0;"
        "   border-radius: 3px;"
        "   padding: 5px;"
        "}"
    );

    // 添加应用按钮
    QPushButton *applyButton = new QPushButton("应用修改");
    applyButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #4CAF50;"
        "   color: white;"
        "   padding: 8px 16px;"
        "   border-radius: 4px;"
        "}"
        "QPushButton:hover { background-color: #45a049; }"
    );
    connect(applyButton, &QPushButton::clicked, this, &JsonConfigView::applyEdits);

    mainLayout->addWidget(m_jsonEdit);
    mainLayout->addWidget(applyButton, 0, Qt::AlignRight);
}

JsonConfigView::~JsonConfigView()
{
    if (m_view) {
        delete m_view;
    }
}

QWidget* JsonConfigView::viewWidget()
{
    return m_view;
}

void JsonConfigView::updateConfig(const QJsonArray &config)
{
    m_originalConfig = config;
    m_currentConfig = config;

    // 显示原始JSON数据
    QJsonDocument doc(m_currentConfig);
    m_jsonEdit->setText(doc.toJson(QJsonDocument::Indented));
}

QJsonArray JsonConfigView::getModifiedConfig() const
{
    return m_currentConfig;
}

void JsonConfigView::applyEdits()
{
    // 解析JSON
    QJsonParseError parseError;
    QJsonDocument doc = QJsonDocument::fromJson(m_jsonEdit->toPlainText().toUtf8(), &parseError);

    if (parseError.error != QJsonParseError::NoError) {
        QMessageBox::warning(nullptr, "JSON解析错误",
                             "JSON格式错误: " + parseError.errorString());
        return;
    }

    if (!doc.isArray()) {
        QMessageBox::warning(nullptr, "JSON格式错误", "配置必须是JSON数组格式");
        return;
    }

    m_currentConfig = doc.array();
    emit configModified();
}

void JsonConfigView::resetToOriginal()
{
    m_currentConfig = m_originalConfig;
    updateConfig(m_currentConfig);
}
